import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  id: '',
  user_title: '',
  departmentNameStr: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_TITLE: (state, user_title) => {
    state.user_title = user_title
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_DEPARTMENTNAMESTR: (state, departmentNameStr) => {
    state.departmentNameStr = departmentNameStr
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password,validate } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: 'admin', phone: username.trim(), password: password,validate:validate }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        const { nickname, avatar, role_name, user_code, department_name } = data
        commit('SET_NAME', nickname)
        commit('SET_ID', user_code)
        commit('SET_TITLE', role_name)
        commit('SET_AVATAR', avatar)
        commit('SET_DEPARTMENTNAMESTR', department_name)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject('token失效，请重新登录')
        }
        const { nickname, avatar, role_name, user_code, department_name } = data

        commit('SET_NAME', nickname)
        commit('SET_ID', user_code)
        commit('SET_TITLE', role_name)
        commit('SET_AVATAR', avatar)
        commit('SET_DEPARTMENTNAMESTR', department_name)

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        removeToken()
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

